from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.utils.translation import gettext_lazy as _
from .models import User, VoiceProfile, SynthesizedAudio


@admin.register(User)
class UserAdmin(BaseUserAdmin):
    """用户管理界面"""
    
    list_display = ['email', 'name', 'role', 'gender', 'is_active', 'is_staff', 'created_at']
    list_filter = ['role', 'gender', 'is_active', 'is_staff', 'created_at']
    search_fields = ['email', 'name', 'phone']
    ordering = ['-created_at']
    
    fieldsets = (
        (None, {'fields': ('email', 'password')}),
        (_('Personal info'), {'fields': ('name', 'gender', 'phone', 'avatar')}),
        (_('Role'), {'fields': ('role',)}),
        (_('Permissions'), {
            'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions'),
        }),
        (_('Important dates'), {'fields': ('last_login', 'created_at', 'updated_at')}),
    )
    
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('email', 'name', 'role', 'gender', 'password1', 'password2'),
        }),
    )
    
    readonly_fields = ['created_at', 'updated_at']
    
    def get_form(self, request, obj=None, **kwargs):
        """重写表单以处理必填字段"""
        form = super().get_form(request, obj, **kwargs)
        if obj is None:  # 创建新用户
            form.base_fields['role'].required = True
        return form


@admin.register(VoiceProfile)
class VoiceProfileAdmin(admin.ModelAdmin):
    """语音配置管理界面"""
    
    list_display = ['name', 'voice_type', 'is_active', 'speed', 'pitch', 'volume', 'created_at']
    list_filter = ['voice_type', 'is_active', 'created_at']
    search_fields = ['name', 'description']
    ordering = ['-created_at']
    
    fieldsets = (
        (None, {'fields': ('name', 'voice_type', 'description')}),
        (_('Audio Settings'), {'fields': ('speed', 'pitch', 'volume')}),
        (_('Media'), {'fields': ('sample_audio_url',)}),
        (_('Status'), {'fields': ('is_active',)}),
        (_('Important dates'), {'fields': ('created_at',)}),
    )
    
    readonly_fields = ['created_at']


@admin.register(SynthesizedAudio)
class SynthesizedAudioAdmin(admin.ModelAdmin):
    """合成音频管理界面"""
    
    list_display = ['question', 'voice_profile', 'duration', 'file_size', 'created_at']
    list_filter = ['voice_profile__voice_type', 'created_at']
    search_fields = ['question__title', 'voice_profile__name', 'text_content']
    ordering = ['-created_at']
    
    fieldsets = (
        (None, {'fields': ('question', 'voice_profile')}),
        (_('Audio File'), {'fields': ('audio_file', 'text_content')}),
        (_('Metadata'), {'fields': ('duration', 'file_size')}),
        (_('Important dates'), {'fields': ('created_at',)}),
    )
    
    readonly_fields = ['created_at'] 